/*
* Copyright (c) 2012 Kyle Hayward
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "Precompiled.h"

#include "Context.h"
#include "Buffer.h"

using namespace System;

namespace OptixDotNet 
{
	Buffer::Buffer( Context^ context ) : DataNode( context )
	{
		mBuffer = 0;
	}

	Buffer::Buffer( Context^ context, BufferDesc desc ) : DataNode( context )
	{
		mBuffer = 0;
		Create( desc );
	}

	void Buffer::Create( BufferDesc% desc )
	{
		mFormat = desc.Format;
		mType = desc.Type;
		mWidth = desc.Width;
		mHeight = desc.Height;
		mDepth = desc.Depth;

		if( mWidth < 0 )
			throw gcnew Exception( "Buffer Width must be >= zero" );

		if( mHeight < 0 )
			throw gcnew Exception( "Buffer Height must be >= zero" );

		if( mDepth < 0 )
			throw gcnew Exception( "Buffer Depth must be >= zero" );

		if( mFormat == OptixDotNet::Format::User && desc.ElemSize <= 0 )
			throw gcnew Exception( "Buffer Error: Invalid ElemSize for User format Buffer." );

		pin_ptr<RTbuffer> ptr = &mBuffer;
		CheckError( rtBufferCreate( mContext->InternalPtr(), (unsigned int )mType, ptr ) );
		CheckError( rtBufferSetFormat( mBuffer, static_cast<RTformat>( mFormat ) ) );
		SetSize( mWidth, mHeight, mDepth );
		
		if( mFormat == OptixDotNet::Format::User )
			CheckError( rtBufferSetElementSize( mBuffer, desc.ElemSize ) ); 
	}

	void Buffer::SetSize( Size width, Size height, Size depth )
	{
		if( height <= 1 && mDepth <= 1 )
			CheckError( rtBufferSetSize1D( mBuffer, width ) );
		else if( depth <= 1 )
			CheckError( rtBufferSetSize2D( mBuffer, width, height ) );
		else
			CheckError( rtBufferSetSize3D( mBuffer, width, height, depth ) );
	}
}